package vesko1.model;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author Vesko
 */
public class PersonDAO {
    
    public static Person findByEgn(String egn) {
        Person person = null;
        try {
            Connection con =  DBConnection.getCon();
            Statement stmt = con.createStatement();
            ResultSet set = stmt.executeQuery("SELECT * FROM person WHERE egn = '" + egn +"';");
            if ( set.next() ) {
                person = new Person(set.getString(1), set.getString(2), 
                                    set.getBoolean(3), set.getString(4), set.getString(5), 
                                    set.getString(6), set.getString(7), set.getBoolean(8));
            }
        }
        catch (Exception e) {
          System.out.println("Cannot find person with egn : " + egn);
        }
        
        return person;
    }
    
    public static void addNewPerson(Person p) {
        try {
            if ( findByEgn(p.getEgn()) == null ) {
                Connection con =  DBConnection.getCon();
                Statement stmt = con.createStatement();

                stmt.executeUpdate("INSERT INTO person values "
                        + "('" + p.getEgn() + "', '" + p.getName() + "',"+ p.isIsPhys() 
                        + ",'" + p.getCity() + "','" + p.getAdress() 
                        + "','"+ p.getPhone() + "','" + p.getEmail() + "'," + String.valueOf(p.isPTP()) + ")" );


                System.out.println("1 new person inserted!");
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        
    }
}
